package cn.wolfcode.luowowo.website.web.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//Cookie工具类
public class CookieUtil {
    //添加
    public static void addCookie(String key, String value, HttpServletResponse response, int time) {
        //将token设置到Cookie对象中,传到浏览器
        Cookie c = new Cookie(key, value);
        c.setPath("/"); //设置共享作用域
        c.setMaxAge(time); //设置最大存活时间
        response.addCookie(c);
    }

    //获取
    public static String getToken(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    //如果在规定时间内有交互,那么就会再次刷新存活时间
                    CookieUtil.addCookie("token",token,response,RedisKeys.USER_LOGIN.getTime().intValue());
                    break;
                }
            }
        }
        return token;
    }
}
